package com.connect.agreement;

import java.nio.ByteBuffer;

import org.xsocket.IDestroyable;

public class Packet implements IPacket, IDestroyable {
	private char mark = 0x1234;
	private int size = 0;
	private char crc = 0;
	private byte groupcmd = 0;
	private byte cmd = 0;
	private char end = 0x4321;
	private byte[] content;
	private ByteBuffer buffer;
	public ByteBuffer byteBuffer(){
		if (this.buffer.position() > 0) {
			this.buffer.flip();
        }
		return buffer;
	}

	public void destroy() {
		if(this.buffer!=null)
			this.buffer.clear();
		this.buffer = null;
	}

	public char getMark() {
		return mark;
	}

	public int getSize() {
		return size;
	}

	public char getCrc() {
		return crc;
	}

	public byte getGroupcmd() {
		return groupcmd;
	}

	public byte getCmd() {
		return cmd;
	}

	public char getEnd() {
		return end;
	}
	
	public void setBuffer(byte groupcmd,byte cmd,byte[] value,boolean iscompress){
		ByteBuffer buffer = null;
		if(iscompress){
			value = new Compress().compress(value);
		}
		if(value!=null){
			buffer = ByteBuffer.allocate(value.length);
			buffer.put(value);
		}
		this.setBuffer(groupcmd, cmd, buffer);
	}
	
	public void setBuffer(byte groupcmd,byte cmd,ByteBuffer value){
		this.groupcmd = groupcmd;
		this.cmd = cmd;
		if(value!=null){
			if(value.position()>0){
				value.flip();
			}
			this.content = value.array();
			this.size = value.limit();
		}
		else
		{
			this.size = 0;
		}
		ByteBuffer tocrc = ByteBuffer.allocate(this.size+2);
		tocrc.put(this.groupcmd);
		tocrc.put(this.cmd);
		if(value != null){
			value.position(0);
			tocrc.put(value);			
		}
		this.crc = CRC16.caluCRC(tocrc.array());
		this.buffer = ByteBuffer.allocate(12+this.size);
		this.buffer.putChar(this.mark);
		this.buffer.putInt(this.size);
		this.buffer.putChar(this.crc);
		this.buffer.put(this.groupcmd);
		this.buffer.put(this.cmd);
		if(value!=null)
		{
			value.position(0);
			this.buffer.put(value);			
		}
		this.buffer.putChar(this.end);
	}
	
	public byte[] getContent(){
		return this.content;
	}
	
	@Override
	public String toString() {
		return "[Packet(size:"+(int)this.size+",crc:"+(int)this.crc+",group:"+(int)this.groupcmd+",cmd:"+this.cmd+",datalen:"+this.buffer.limit()+")]";
	}
}
